<template>
  <div class="announcement-detail-container">
    <div class="detail-header">
      <el-button @click="goBack" type="text" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>

    <div v-if="announcement" class="announcement-content">
      <div class="announcement-header">
        <h1 class="announcement-title">{{ announcement.title }}</h1>
        <div class="announcement-meta">
          <el-tag :type="getTypeTagType(announcement.type)" class="type-tag">
            {{ getTypeText(announcement.type) }}
          </el-tag>
          <el-tag 
            :type="announcement.priority === 'high' ? 'danger' : 
                   announcement.priority === 'medium' ? 'warning' : 'info'"
            class="priority-tag"
          >
            {{ getPriorityText(announcement.priority) }}优先级
          </el-tag>
          <span class="publish-time">
            发布时间：{{ formatTime(announcement.publish_time || announcement.publishTime) }}
          </span>
        </div>
      </div>

      <div class="announcement-body">
        <div class="content-text">
          {{ announcement.content }}
        </div>
      </div>

      <div class="announcement-footer">
        <div class="share-section">
          <span>分享到：</span>
          <el-button link @click="shareToWechat">
            <el-icon><ChatDotRound /></el-icon>
            微信
          </el-button>
          <el-button link @click="shareToWeibo">
            <el-icon><Share /></el-icon>
            微博
          </el-button>
          <el-button link @click="copyLink">
            <el-icon><Link /></el-icon>
            复制链接
          </el-button>
        </div>
      </div>
    </div>

    <div v-else class="not-found">
      <el-empty description="公告不存在或已被删除">
        <el-button type="primary" @click="goBack">返回首页</el-button>
      </el-empty>
    </div>

    <!-- 相关公告 -->
    <div v-if="relatedAnnouncements.length > 0" class="related-section">
      <h3>相关公告</h3>
      <div class="related-list">
        <div 
          v-for="item in relatedAnnouncements" 
          :key="item.id"
          class="related-item"
          @click="viewAnnouncement(item.id)"
        >
          <div class="related-title">{{ item.title }}</div>
          <div class="related-date">{{ formatTime(item.publish_time || item.publishTime) }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getAnnouncementDetail, getAnnouncements } from '../api/announcement';
import {
  ArrowLeft,
  ChatDotRound,
  Share,
  Link
} from '@element-plus/icons-vue';

export default {
  name: 'AnnouncementDetail',
  components: {
    ArrowLeft,
    ChatDotRound,
    Share,
    Link
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const announcement = ref(null);
    const relatedAnnouncements = ref([]);

    // 获取公告详情
    const fetchAnnouncement = async () => {
      try {
        const announcementId = parseInt(route.params.id);

        // 首先尝试从API获取
        const response = await getAnnouncementDetail(announcementId);
        if (response.success) {
          announcement.value = response.data;

          // 获取相关公告
          await fetchRelatedAnnouncements(response.data.type, announcementId);
        } else {
          throw new Error('API响应失败');
        }
      } catch (error) {
        console.error('获取公告详情失败:', error);

        // API失败时，尝试从localStorage获取
        const storedActivities = localStorage.getItem('activities');
        if (storedActivities) {
          const activities = JSON.parse(storedActivities);
          const activity = activities.find(activity => activity.id === parseInt(route.params.id));

          if (activity) {
            announcement.value = activity;

            // 获取相关公告（同类型的其他公告）
            relatedAnnouncements.value = activities
              .filter(a =>
                a.id !== activity.id &&
                a.type === activity.type &&
                a.status === 'published'
              )
              .slice(0, 5);
          }
        }
      }
    };

    // 获取相关公告
    const fetchRelatedAnnouncements = async (type, currentId) => {
      try {
        const response = await getAnnouncements({ type, pageSize: 10 });
        if (response.success) {
          relatedAnnouncements.value = response.data.announcements
            .filter(item => item.id !== currentId)
            .slice(0, 5);
        }
      } catch (error) {
        console.error('获取相关公告失败:', error);
      }
    };

    // 返回上一页
    const goBack = () => {
      router.go(-1);
    };

    // 查看其他公告
    const viewAnnouncement = (id) => {
      router.push(`/announcement/${id}`);
    };

    // 分享功能
    const shareToWechat = () => {
      ElMessage.info('微信分享功能开发中...');
    };

    const shareToWeibo = () => {
      ElMessage.info('微博分享功能开发中...');
    };

    const copyLink = () => {
      const url = window.location.href;
      navigator.clipboard.writeText(url).then(() => {
        ElMessage.success('链接已复制到剪贴板');
      }).catch(() => {
        ElMessage.error('复制失败');
      });
    };

    // 辅助方法
    const getTypeText = (type) => {
      const typeMap = {
        system: '系统公告',
        activity: '活动通知',
        maintenance: '维护通知',
        promotion: '优惠活动'
      };
      return typeMap[type] || '未知';
    };

    const getTypeTagType = (type) => {
      const typeMap = {
        system: 'primary',
        activity: 'success',
        maintenance: 'warning',
        promotion: 'danger'
      };
      return typeMap[type] || 'info';
    };

    const getPriorityText = (priority) => {
      const priorityMap = {
        high: '高',
        medium: '中',
        low: '低'
      };
      return priorityMap[priority] || '中';
    };

    const formatTime = (timeStr) => {
      if (!timeStr) return '';
      return new Date(timeStr).toLocaleString('zh-CN');
    };

    onMounted(() => {
      fetchAnnouncement();
    });

    return {
      announcement,
      relatedAnnouncements,
      goBack,
      viewAnnouncement,
      shareToWechat,
      shareToWeibo,
      copyLink,
      getTypeText,
      getTypeTagType,
      getPriorityText,
      formatTime
    };
  }
};
</script>

<style scoped>
.announcement-detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  min-height: calc(100vh - 120px);
}

.detail-header {
  margin-bottom: 20px;
}

.back-btn {
  color: #409eff;
  font-size: 14px;
}

.back-btn:hover {
  color: #66b1ff;
}

.announcement-content {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.announcement-header {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 20px;
  margin-bottom: 30px;
}

.announcement-title {
  font-size: 28px;
  color: #303133;
  margin: 0 0 15px 0;
  line-height: 1.4;
}

.announcement-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.type-tag, .priority-tag {
  font-size: 12px;
}

.publish-time {
  color: #909399;
  font-size: 14px;
}

.announcement-body {
  margin-bottom: 30px;
}

.content-text {
  font-size: 16px;
  line-height: 1.8;
  color: #606266;
  white-space: pre-wrap;
}

.announcement-footer {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.share-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.share-section span {
  color: #909399;
  font-size: 14px;
}

.not-found {
  text-align: center;
  padding: 60px 20px;
}

.related-section {
  margin-top: 40px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.related-section h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 18px;
}

.related-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.related-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.related-item:hover {
  background: #f0f9ff;
  transform: translateX(5px);
}

.related-title {
  color: #303133;
  font-size: 14px;
  flex: 1;
}

.related-date {
  color: #909399;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .announcement-detail-container {
    padding: 15px;
  }
  
  .announcement-content {
    padding: 20px;
  }
  
  .announcement-title {
    font-size: 24px;
  }
  
  .announcement-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .share-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .related-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>
